import commonOperator from '../../common/opinterface/commonOperator.js';
import config from '../config/config.js'
import Log from '../../common/util/log.js'

const JS_TAG = 'JS/Common/Permission helper: ';

var onCheckPermissionResult = (callbackJson) => {
    Log.debug(JS_TAG + 'Check permission result: ' + JSON.stringify(callbackJson));
    if (callbackJson.data.granted.length == callbackJson.data.requested.length) {
        Log.debug(JS_TAG + 'All permissions granted');
        promiseParams.resolve();
        return;
    }
    let grantedPermissions = callbackJson.data.granted;
    let canRequestPermissions = callbackJson.data.canRequest;
    for (let permission of config.mandatoryPermissions) {
        if (!grantedPermissions.includes(permission) && !canRequestPermissions.includes(permission)) {
            Log.debug(JS_TAG + 'Permission: ' + permission + 'is forbidden.');
            promiseParams.reject({
                permissionForbidden: true
            });
            return;
        }
    }

    if (canRequestPermissions.length > 0) {
        Log.debug(JS_TAG + 'Permission can still be requested:');
        requestPermissions(canRequestPermissions);
    } else {
        Log.debug(JS_TAG + 'Permission cannot be requested, but mandatory permissions is granted:');
        promiseParams.resolve(true);
    }
}

var requestPermissions = (permissionsRequired) => {
    commonOperator.requestPermission(permissionsRequired, config.permissionRequestCode, onPermissionRequestResult);
}

var onPermissionRequestResult = (callbackJson) => {
    Log.debug(JS_TAG + 'Request permission result: ' + JSON.stringify(callbackJson));
    if (callbackJson.data.granted.length == callbackJson.data.requested.length) {
        Log.debug(JS_TAG + 'All permissions granted');
        promiseParams.resolve();
        return;
    }
    let grantedPermissions = callbackJson.data.granted;

    for (let permission of config.mandatoryPermissions) {
        if (!grantedPermissions.includes(permission)) {
            Log.debug(JS_TAG + 'Permission: ' + permission + 'is forbidden.');
            promiseParams.reject({
                permissionForbidden: false
            });
            return;
        }
    }
    Log.debug(JS_TAG + 'Mandatory permissions is granted:');
    promiseParams.resolve(true);
}

var promiseParams = {}

export default {
    data: {},
    checkAndRequestPermission() {
        let promise = new Promise((resolve, reject) => {
            promiseParams.resolve = resolve;
            promiseParams.reject = reject;
            commonOperator.checkPermission(config.permissions, onCheckPermissionResult);
        })
        return promise;
    }
}